package com.xyj.service.impl;

import com.xyj.dao.MenuDaoI;
import com.xyj.domain.TMenu;
import com.xyj.pageModel.Menu;
import com.xyj.service.MenuServiceI;
import com.xyj.util.LoggerUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Created by 徐宇健 on 2015/2/12 0012.
 */
@Service("menuService")
public class MenuServiceImpl implements MenuServiceI {
    private MenuDaoI menuDao;

    public MenuDaoI getMenuDao() {
        return menuDao;
    }
    @Autowired
    public void setMenuDao(MenuDaoI menuDao) {
        this.menuDao = menuDao;
    }

    @Override
    public List<Menu> getMenuTree(String id) {
        String hql = "";
        Map params = new HashMap<String ,Object>();
        if (StringUtils.isEmpty(id)){
            hql = "from TMenu t where t.tMenuByTid is null";
        }else {
            //查询子节点
            hql = "from TMenu t where t.tMenuByTid.id =:id";
            params.put("id",id);
        }

        List<TMenu> tMenus =  menuDao.find(hql, params);
        List<Menu> menus = new ArrayList<>();
        for ( TMenu m :tMenus){
            Menu menu = new Menu();
            BeanUtils.copyProperties(m,menu);
            menu.setText(m.getName());
            Collection s =  m.gettMenusById();
            if( s!= null && s.size()>0){
                menu.setState("closed");
            }else {
                menu.setState("open");
            }
            menus.add(menu);
        }
        return menus;
    }

    @Override
    public List<Menu> getAllMenuTrees() {
        List<TMenu> tMenus =  menuDao.find("from TMenu",null);
        List<Menu> menus = new ArrayList<>();
        for ( TMenu m :tMenus){
            Menu menu = new Menu();
            BeanUtils.copyProperties(m,menu);
            menu.setText(m.getName());
            TMenu tm = m.gettMenuByTid();
            if(tm!=null){
                menu.setPid(tm.getId());
            }
            menu.getAttributes().put("url",m.getUrl());
            menus.add(menu);
        }
        return menus;
    }
}
